package com.itheima.util;


import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionUtil {
    //会话工厂
    private static SqlSessionFactory sqlSessionFactory;

    //1. 在静态代码块中创建会话工厂对象
    static {
        String config = "mybatis-config.xml";
        try {
            InputStream in = Resources.getResourceAsStream(config);

            sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //2. 编写静态方法得到会话对象，设置自动提交事务
    // 会话 : SqlSession
    public static SqlSession getSession() {
        return sqlSessionFactory.openSession(true);//自动提交
    }

    //3. 编写静态方法得到会话对象，方法接收调用者传递的布尔类型参数，参数决定是否自动提交事务
    public static SqlSession getSession(boolean autoCommit) {
        return sqlSessionFactory.openSession(autoCommit);//是否自动提交，由autoCommit控制
    }

    //4. 编写静态方法接收会话对象，手动提交事务并且关闭会话
    public static void commitAndClose(SqlSession session) {
        if (session!=null) {
            //提交
            session.commit();
            //关闭
            session.close();
        }
    }

    //5. 编写静态方法接收会话对象，回滚事务并且关闭会话
    public static void rollbackAndClose(SqlSession session) {
        if (session!=null) {
            //回滚
            session.rollback();
            //关闭
            session.close();
        }
    }
}
